package com.smarthome.web.property.controller.housemanager;

import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSONObject;
import com.smarthome.core.housemanager.ResidenceFeeService;
import com.smarthome.core.housemanager.ResidenceManagerService;
import com.smarthome.core.propertystaffmanager.PropertyCompanyService;
import com.smarthome.core.user.UserRoleService;
import com.smarthome.domain.bean.ShAreaCity;
import com.smarthome.domain.bean.ShAreaDistrict;
import com.smarthome.domain.bean.ShAreaProvince;
import com.smarthome.domain.bean.ShPropertyCompany;
import com.smarthome.domain.bean.ShResidence;
import com.smarthome.domain.bean.ShResidenceFee;
import com.smarthome.domain.bean.ShUserRole;
import com.smarthome.domain.common.Result;
import com.smarthome.domain.vo.boss.Combobox;
import com.smarthome.domain.vo.boss.DataGrid;
import com.smarthome.domain.vo.boss.PageHelper;
import com.smarthome.domain.vo.boss.Tree;
import com.smarthome.web.property.utils.AreaUtil;
import com.smarthome.web.property.utils.UserHolder;

/**
 * @author dhc
 * @title 小区管理
 */
@Controller
@RequestMapping("/residenceController")
public class ResidenceManagerController {
		
	@Resource(name="residenceManagerService")
    private ResidenceManagerService residenceManagerService;
	
	@Resource(name="propertyCompanyService")
	private PropertyCompanyService propertyCompanyService;
	
	@Resource(name="userRoleService")
	private UserRoleService userRoleService;
	
	@Resource(name="residenceFeeService")
	private ResidenceFeeService residenceFeeService;
	
	/**
	 * @param residence
	 * @param helper
	 * @param request
	 * @return
	 */
	@RequestMapping("/dataGrid")
    @ResponseBody
	public DataGrid getPage(ShResidence residence,PageHelper helper,HttpServletRequest request){
		if(!UserHolder.isSuperResidence()){
			if(null == residence) residence = new ShResidence();
			residence.setId(UserHolder.getCurrentResidenceId());
		}
		
		DataGrid grid = residenceManagerService.getDataGrid(residence, helper);
		//添加区域名字
		if(null != grid && null != grid.getRows()){
 			for(Object obj : grid.getRows()){
				if(null != obj && obj instanceof ShResidence){
					ShResidence r = (ShResidence)obj;
					String areaName = "";
					if(null == r.getAreaId()) continue;
					try{
						ShAreaDistrict  d = AreaUtil.getDistrict(r.getAreaId());
						areaName = d.getDistrictName();
						ShAreaCity city = AreaUtil.getCity(d.getCityId());
						areaName = city.getCityName() + " " + areaName;
						ShAreaProvince province = AreaUtil.getProvince(city.getProvinceId());
						areaName = province.getProvinceName()+ " " + areaName;
					} catch(Exception e){e.printStackTrace();}
					r.setAreaName(areaName);
				}
				
			}
		}
		
		return grid;
	}
	
	@RequestMapping("/tree")
    @ResponseBody
	public List<Tree> getTree(HttpServletRequest request){
		return residenceManagerService.getTree();
	}
	
	@RequestMapping("/combobox")
	@ResponseBody
	public List<Combobox> getCombobox(){
		return residenceManagerService.getCombobox();
	}
	
	@RequestMapping("/addPage")
    public String addPage(HttpServletRequest request) {
		
		request.setAttribute("propertyCompany", propertyCompanyService.getComboboxs(getCompany()));
        return "/housemanager/residenceAdd";
	}
	
	@RequestMapping("/propertyPage")
	public String propertyPage(HttpServletRequest request) {
		request.setAttribute("propertyCompany", propertyCompanyService.getComboboxs(getCompany()));
		return "/housemanager/propertyPage";
	}
	@RequestMapping("/editPage")
	public String eidtPage(HttpServletRequest request,Long id) {
		request.setAttribute("residence", residenceManagerService.queryResidenceById(id));
		request.setAttribute("propertyCompany", propertyCompanyService.getComboboxs(getCompany()));
		return "/housemanager/residenceEdit";
	}
	/**
	 * @param request
	 * @title 分配资源
	 */
	@RequestMapping("/dispatchResourcePage")
	public String dispatchResourcePage(HttpServletRequest request,Long id) {
		ShUserRole role = userRoleService.UserRoleRootByResidenceId(id);
		ShResidence residence = residenceManagerService.queryResidenceById(id);
		if(null == role){
			role = new ShUserRole();
			role.setName("【" + residence.getName() + "】角色组" );
		}
		role.setResidence(residence);
		role.setResidenceId(residence.getId());
		role.setResidenceName(residence.getName());
		request.setAttribute("role", role);
		return "/housemanager/resourcePage";
	}
	
	/**
	 * @param request
	 * @title 指定物业公司
	 */
	@RequestMapping("/dispatchPropertyPage")
	public String dispatchPropertyPage(HttpServletRequest request,Long id) {
		request.setAttribute("residence", residenceManagerService.queryResidenceById(id));
		request.setAttribute("propertyCompany", propertyCompanyService.getComboboxs(getCompany()));
		return "/housemanager/propertyPage";
	}
	/**
	 * @param request
	 * @title 物业费用设置页面
	 */
	@RequestMapping("/dispatchPropertyFeePage")
	public String dispatchPropertyFeePage(HttpServletRequest request,Long id) {
		ShResidence residence = residenceManagerService.queryResidenceById(id);
		request.setAttribute("residence", residence);
		//查询物业费设置
		ShResidenceFee fee =residenceFeeService. residenceFeeNoNullByResidenceId(id);
		if(null !=fee && StringUtils.isBlank(fee.getName())){
			fee.setName("【" + residence.getName()  + "】物业费设置" );
		}
		request.setAttribute("fee",fee);
		return "/housemanager/propertyFeePage";
	}
	
	  @RequestMapping("/add")
	  @ResponseBody
	  public Result add(ShResidence residence) {
		  if(StringUtils.isBlank(residence.getName())){
			  return Result.failure("添加失败，小区名字为必填！");
		  }
		  if(StringUtils.isBlank(residence.getCode())){
			  return Result.failure("添加失败，小区编码为必填！");
		  }
		  
		  if(StringUtils.isBlank(residence.getCode())){
			  return Result.failure("添加失败，小区编码为必填！");
		  }
		  if(StringUtils.isBlank(residence.getAddress())){
			  return Result.failure("添加失败，小区地址为必填！");
		  }
		  
		  try{
			  residenceManagerService.add(residence);
		  } catch(Exception e){
			  e.printStackTrace();
			  return Result.failure(e.getMessage());
			  
		  }
	      return Result.success("添加成功！");
	    }
	  
	  @RequestMapping("/edit")
	  @ResponseBody
	  public Result edit(ShResidence residence) {
		  
		  if(StringUtils.isBlank(residence.getName())){
			  return Result.failure("编辑失败，小区名字为必填！");
		  }
		  if(StringUtils.isBlank(residence.getCode())){
			  return Result.failure("编辑失败，小区编码为必填！");
		  }
		  
		  if(StringUtils.isBlank(residence.getCode())){
			  return Result.failure("编辑失败，小区编码为必填！");
			   
		  }
		  if(StringUtils.isBlank(residence.getAddress())){
			  return Result.failure("编辑失败，小区地址为必填！");
		  }
		  
		  residenceManagerService.edit(residence);
		  return Result.success("编辑成功！");
	  }
	  
	  @RequestMapping("/delete")
	  @ResponseBody
	  public Result delete(Long id) {
		  try{
			  int count = residenceManagerService.delte(id);
			  if(count == 0){
				  return Result.failure("小区被引用，不能删除");
			  }
		  } catch(Exception e){
			  return Result.failure("小区被引用，不能删除");
		  }
		  return Result.success("删除成功！");
	  }
	
	  @RequestMapping("/dispatchProperty")
	  @ResponseBody
	  public Result dispatchProperty(ShResidence residence) {
		  if(null == residence.getId()){
			  return Result.failure("指定物业公司失败");
		  }
		  
		  if(null == residence.getPropertyId()){
			 //return Result.failure("请指定一个物业公司");
		  }
		  
		  ShResidence qr =  residenceManagerService.queryResidenceById(residence.getId());
		  qr.setPropertyId(residence.getPropertyId());
		  residenceManagerService.edit(qr);
		  return Result.success("指定物业公司成功！");
	  }
	  
	  @RequestMapping("/dispatchResource")
	  @ResponseBody
	  public Result dispatchResource(ShUserRole role) {
		  //验证
		  if(role.getResidenceId() == null){
			  return Result.failure("资源分配不成功");
		  }
		  if(StringUtils.isBlank(role.getName())){
			  return Result.failure("资源名称不能为空");
		  }
		  
		  //重名验证
		  if(userRoleService.isRepeat(role)){
			  return Result.failure("角色资源名称重复");
		  }
		  
		  if(null == role.getId()){
			  role.setParentId(0l);
			  userRoleService.add(role);
			  return Result.success("分配资源成功！");
		  } 
		  ShUserRole qr = userRoleService.queryPropertyRoleById(role.getId());
		  if(null != qr){
			  qr.setResidenceId(role.getResidenceId());
			  qr.setName(role.getName());
			  qr.setRemark(role.getRemark());
			  qr.setSortWeight(role.getSortWeight());
			  userRoleService.edit(qr);		  
			  
		  } else{
			  return Result.failure("分配资源出现异常");
		  }
		  
		  return Result.success("资源名称不能为空");
	  }
	
	
	  /***
	   * @title 物业费用设置
	   * @createTime 2015年9月23日 下午9:19:29
	   * @author dhc
	   */
		@RequestMapping("/dispatchPropertyFee")
		 @ResponseBody
		public Result dispatchPropertyFeePage(HttpServletRequest request,ShResidenceFee residenceFee) {
			if(null == residenceFee.getResidenceId()) 
				return Result.failure("未指定小区");
			
			//验证
			if(StringUtils.isBlank(residenceFee.getName())){
				
				//return Result.failure("名字不能为空");
			}
			
			residenceFeeService.edit(residenceFee);
			return Result.success("物业费设置成功");
		
		}
		
		private ShPropertyCompany getCompany(){ 
			ShPropertyCompany company = new ShPropertyCompany();
			if(!UserHolder.isSuperResidence()){
				//company.setResidenceId(UserHolder.getCurrentResidenceId());
			}
			
			return company;
		}
		
		/**
		 * 
		* @Title: relResidenceExpress
		* @Description: 跳转关联小区和快递公司
		* @param residence
		* @param request
		* @return 
		* String  
		* @throws
		 */
		@RequestMapping("/relResidenceExpress")
		public String relResidenceExpress(ShResidence residence,HttpServletRequest request) {
			request.setAttribute("expressTree", JSONObject.toJSON(residenceManagerService.getCompanyExpressByResidence(residence)));
			request.setAttribute("residenceId", residence.getId());
			return "/housemanager/residenceExpress";
		}
		
		/**
		 * 
		* @Title: saveResidenceExpress 
		* @Description: 保存小区和快递公司的关联 
		* @param expressIds
		* @param residenceId
		* @return
		* Result
		* @throws 
		* @author cyj
		 */
		@RequestMapping("/saveResidenceExpress")
		@ResponseBody
		public Result saveResidenceExpress(String expressIds,Long residenceId) {
			try{
				residenceManagerService.saveResidenceExpress(expressIds, residenceId);
			}catch(Exception e) {
				e.printStackTrace();
				return Result.success("系统异常，关联快递公司设置失败");
			}
			return Result.success("关联快递公司设置成功");
		}
		
		
		/**
		 * 
		* @Title: relResidenceLaundry 
		* @Description: 调整关联小区和洗衣店页面 
		* @param residence
		* @param request
		* @return
		* String
		* @throws 
		* @author cyj
		 */
		@RequestMapping("/relResidenceLaundry")
		public String relResidenceLaundry(ShResidence residence,HttpServletRequest request) {
			request.setAttribute("laundryTree", JSONObject.toJSON(residenceManagerService.getCompanyLaundryByResidence(residence)));
			request.setAttribute("residenceId", residence.getId());
			return "/housemanager/residenceLaundry";
		}
		
		
		/**
		 * 
		* @Title: saveResidenceLaundry 
		* @Description: 保存小区与洗衣店的关联 
		* @param laundryIds
		* @param residenceId
		* @return
		* Result
		* @throws 
		* @author cyj
		 */
		@RequestMapping("/saveResidenceLaundry")
		@ResponseBody
		public Result saveResidenceLaundry(String laundryIds,Long residenceId) {
			try{
				residenceManagerService.saveResidenceLaundry(laundryIds, residenceId);
			}catch(Exception e) {
				e.printStackTrace();
				return Result.success("系统异常，关联洗衣店设置失败");
			}
			return Result.success("关联洗衣店设置成功");
		}
	
}
